package com.example.sistemacompras;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.List;

import android.app.Activity;
import android.content.Context;
import android.content.res.Resources;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;

import com.example.sistemacompras.db.DatabaseHandler;
import com.example.sistemacompras.entity.Order;

public class CustomOrderAdapter extends BaseAdapter {

	private Activity activity;
	private List<Order> data;
	private static LayoutInflater inflater = null;
	public Resources res;
	Order tempValues = null;
	// int i = 0;
	private DatabaseHandler db;
	SimpleDateFormat formatter;

	public CustomOrderAdapter(Activity a, List<Order> mOrders,
			Resources resLocal) {
		db = new DatabaseHandler(a);
		activity = a;
		data = mOrders;
		res = resLocal;
		formatter = new SimpleDateFormat("dd/MM/yyyy");
		inflater = (LayoutInflater) activity
				.getSystemService(Context.LAYOUT_INFLATER_SERVICE);

	}

	@Override
	public int getCount() {
		if (data.size() <= 0)
			return 1;
		return data.size();
	}

	@Override
	public Object getItem(int position) {
		return position;
	}

	@Override
	public long getItemId(int position) {
		// TODO Auto-generated method stub
		return position;
	}

	public static class ViewHolder {

		public TextView nameTextVIew;
		public TextView qtdTextView;
		public TextView vlTotalTextView;
	}

	@Override
	public View getView(int position, final View view, ViewGroup viewGroup) {
		View vi = view;
		ViewHolder holder;

		if (view == null) {

			vi = inflater.inflate(R.layout.order_item, null);

			holder = new ViewHolder();
			holder.nameTextVIew = (TextView) vi.findViewById(R.id.name);
			holder.qtdTextView = (TextView) vi.findViewById(R.id.qtd);
			holder.vlTotalTextView = (TextView) vi
					.findViewById(R.id.ValorTotal);

			vi.setTag(holder);
		} else
			holder = (ViewHolder) vi.getTag();

		if (data.size() <= 0) {
			holder.nameTextVIew.setText("No Data");

		} else {

			tempValues = new Order();
			tempValues = (Order) data.get(position);

			holder.nameTextVIew.setText("Compra : "
					+ String.valueOf(tempValues.getId()));

			holder.qtdTextView.setText("Data : "
					+ formatter.format(tempValues.getDate()));

			 holder.vlTotalTextView.setText("R$ " +
			 String.valueOf(db.getOrderValueTotal(tempValues)));
			// holder.deleteButton.setOnClickListener(new OnClickListener() {
			//
			// @Override
			// public void onClick(View v) {
			// db.deleteOrderDetail(tempValues);
			// }
			// });

			// vi.setOnClickListener(new OnItemClickListener( position ));
		}
		return vi;
	}

}
